package com.master.wifimaster;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.master.db.DBHelper;

/**
 * Servlet implementation class WifiAPQuery
 */
@WebServlet("/WifiAPQuery")
public class WifiAPQuery extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WifiAPQuery() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		ServletInputStream in = request.getInputStream();
		ObjectMapper mapper = new ObjectMapper();
		APList reqList = mapper.readValue(in, APList.class);
		
		if (reqList == null) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		try {
			Connection con = DBHelper.getReadConnection();
			PreparedStatement pst = con.prepareStatement("select pwd from tb_wifiap where mac=?");
			ResultSet rst = null;
			APPwdList respList = new APPwdList();
			List<AccessPoint> apList = reqList.getWifiList();
			for(AccessPoint ap : apList) {
				pst.setString(1, ap.getMac());
				rst = pst.executeQuery();
				if(rst.next()) {
					AccessPointPwd pAP = new AccessPointPwd(ap);
					pAP.setPwd(rst.getString(1));
					respList.addAccessPoint(pAP);
				} else {
					AccessPointPwd pAP = new AccessPointPwd(ap);
					pAP.setCode(1);
					respList.addAccessPoint(pAP);
				}
				rst.close();
			}
			pst.close();
			con.close();
			out.print(mapper.writeValueAsString(respList));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
